<template>
    <z-modal
      v-bind="modalOption"
      :footer="null"
      @cancel="handleCancel"
    >
      <vxe-toolbar>
        <template #buttons>
          <vxe-button icon="vxe-icon-square-plus" @click="insertEvent()">新增</vxe-button>
        </template>
      </vxe-toolbar>
      <a-spin :spinning="confirmLoading">
        <vxe-table
          border
          show-overflow
          keep-source
          ref="xTable"
          max-height="400"
          row-id="id"
          :data="tableData"
          :loading="loading"
          :column-config="{resizable: true}"
          :edit-config="{trigger: 'manual', mode: 'row',showStatus: true}"
          >
          <vxe-column field="content" title="计划节点内容" width="200" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.content" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="username" title="计划节点人员" width="300" :edit-render="{}">
            <template #edit="{ row }">
              <z-search-select-tag placement="请选择成员" v-model="row.username" url="/user/list" optionValue="username" optionText="nickname" :getPopupContainer="getPopupContainer" @change="(...rest) => selectUser(row, ...rest)"/>
            </template>
            <template #default="{ row }">
              <p class="plan-node">{{row.nickname ||  ''}}</p>
            </template>
          </vxe-column>
          <vxe-column field="leadingDept" title="计划节点牵头部门" width="200" :edit-render="{}">
            <template #edit="{ row, column }">
              <ZSelectDept v-model.trim="row.leadingDept" @change="(...rest) => {selectDept(row, column,  ...rest)}" :disabled="disableSubmit" :getPopupContainer="getPopupContainer"/>
            </template>
            <template #default="{ row }">
              <p class="plan-node">{{(row._leadingDept ? row._leadingDept.deptName : '')}}</p>
            </template>
          </vxe-column>
          <vxe-column field="cooperateDept" title="计划节点配合部门" width="200" :edit-render="{}">
            <template #edit="{ row,column }">
              <ZSelectDept :multiple="true" v-model.trim="row.cooperateDept" @change="(...rest) => {selectDept(row, column, ...rest)}" :disabled="disableSubmit" :getPopupContainer="getPopupContainer"/>
            </template>
            <template #default="{ row }">
              <p class="plan-node">{{(row._cooperateDept || []).map(item => item.deptName).join(',')}}</p>
            </template>
          </vxe-column>
          <vxe-column field="progress" title="计划节点进度" width="200" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.progress" type="number" min="0" max="100" placeholder="请输入数值">
                <template #suffix>
                  %
                </template>
              </vxe-input>
            </template>
            <template #default="{ row }">
              <p class="plan-node">{{row.progress?row.progress:0}}%</p>
            </template>
          </vxe-column>
          <vxe-column field="startTime" title="计划节点开始时间" width="200" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.startTime" type="date" placeholder="请选择日期" transfer></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="endTime" title="计划节点完成时间" width="200" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.endTime" type="date" placeholder="请选择日期" transfer></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="status" title="计划节点是否完成" width="200" :edit-render="{}">
            <template #edit="{ row }">
              <p class="plan-node">{{(row.status === '1' ? '已完成' : '未完成')}}</p>
            </template>
            <template #default="{ row }">
              <p class="plan-node">{{(row.status === '1' ? '已完成' : '未完成')}}</p>
            </template>
          </vxe-column>
          <vxe-column field="attach" title="附件" width="200" :edit-render="{}">
            <template #edit="{}">
              <p class="plan-node disable-txt">请从上传入口进行编辑</p>
            </template>
            <template #default="{ row }">
              <a-dropdown :trigger="['click']" @visibleChange="(visible) => handleVisibleChange(row, visible)">
                <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                  查看附件<a-icon type="down" />
                </a>
                <a-menu slot="overlay" v-if="row.attachList && row.attachList.length">
                  <a-menu-item v-for="(item, index) in row.attachList" :key="item.id">
                    <a target="_blank" :href="item.attachUrl">
                      查看附件{{ index + 1 }}
                      <a-divider type="vertical" />
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDeleteAttach(row, item, index)">
                        <a-icon type="delete" @click="(evt) => {evt.stopPropagation(); evt.preventDefault();}"/>
                      </a-popconfirm>
                    </a>
                  </a-menu-item>
                </a-menu>
                <a-menu slot="overlay" v-else>
                  <a-menu-item>暂无附件</a-menu-item>
                </a-menu>
              </a-dropdown>
            </template>
          </vxe-column>
          <vxe-column title="操作" width="190" fixed='right'>
            <template #default="{ row }">
              <template v-if="$refs.xTable.isActiveByRow(row)">
                <vxe-button type="text" status="primary" @click="saveRowEvent(row)">保存</vxe-button>
                <vxe-button type="text" status="primary" @click="cancelRowEvent(row)">取消</vxe-button>
              </template>
              <template v-else>
                <a @click="editRowEvent(row)">编辑</a>
                <a-divider type="vertical" />
                <a @click="deleteRowEvent(row)">删除</a>
                <a-divider type="vertical" />
                <a-dropdown v-show="!row.isAdd">
                  <a>更多 <a-icon type="down" /></a>
                  <a-menu slot="overlay">
                    <a-menu-item>
                      <a @click="handleAccomplish(row)">{{row.status === '1' ?  '设置未完成' : '设置已完成'}}</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a-upload
                          :class="{'disabled-upload':disableSubmit}"
                          :action="uploadAction"
                          :multiple="false"
                          :file-list="fileList"
                          :headers="headers"
                          :beforeUpload="beforeUpload"
                          @change="(info) => handleChange(row, info)"
                          :showUploadList="false"
                      >
                        <a class="upload-txt">上传附件</a>
                      </a-upload>
                    </a-menu-item>
                  </a-menu>
                </a-dropdown>
              </template>
            </template>
          </vxe-column>
        </vxe-table>
        <vxe-pager
          :loading="loading"
          :current-page="tablePage.currentPage"
          :page-size="tablePage.pageSize"
          :total="tablePage.totalResult"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']"
          @page-change="handlePageChange">
        </vxe-pager>

      </a-spin>
    </z-modal>
  </template>

<script>
import ModalFormMixin from '@/mixins/ModalFormMixin'
import ZSelectDept from '@/components/zzbiz/ZSelectDept'
import moment from 'moment'
import ZSearchSelectTag from '@/components/business/ZSearchSelectTag'
import { addPlanNode, getPlanNodeList, deletePlanNode, editPlanNode, accomplishNode, unaccomplishNode, getAttach, addAttach, removeAttach } from '@/services/schedule'
import VXETable from 'vxe-table'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Upload as AUpload } from 'ant-design-vue'
import { mapGetters } from 'vuex'
export default {
  name: 'ScheduleNodeModal',
  components: { ZSearchSelectTag, ZSelectDept, AUpload },
  mixins: [ModalFormMixin],
  data() {
    return {
      loading: false,
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0
      },
      tableData: [],
      validatorRules: {
        source: [{ required: true, message: '请输入分解来源' }],
        category: [{ required: true, message: '请输入工作大类' }],
        priority: [{ required: true, message: '请输入重点工作' }],
        responsibleDepts: [{ required: true, message: '请输入主责部门' }],
        leaderName: [{ required: true, message: '请输入分管领导' }],
        completionMark: [{ required: true, message: '请输入完成标志' }],
        startEndTime: [{ required: true, message: '请输入起止时间' }]
      },
      url: {
        list: '/plan/schedule/content/v1/page'
      },
      uploadAction: process.env.VUE_APP_API_BASE_URL + '/common/v1/upload',
      fileList: [],
      headers: {}
    }
  },
  watch: {
    visible(nVal, oVal) {
      if (!oVal && nVal) {
        this.loadData()
      }
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  created() {
    this.headers[ACCESS_TOKEN] = this.token
  },
  methods: {
    async handleDeleteAttach(row, item, index) {
      const res = await removeAttach(item.id)
      if (res && res.code === 200) {
        this.$message.success('删除成功！')
        this.handleVisibleChange(row, true)
      } else {
        this.$message.error('删除失败！')
      }
    },
    async handleVisibleChange(row, visible) {
      if (!visible) { return }
      if (row.isAdd) { return }
      const res = await getAttach(row.id)
      if (res && res.code === 200) {
        row.attachList = [...res.result]
      }
    },
    async handleAccomplish(row) {
      const $table = this.$refs.xTable
      let res = row
      if (row.status === '1') {
        // 设置未完成
        res = await unaccomplishNode(row.id)
      } else {
        // 设置已完成
        res = await accomplishNode(row.id)
      }
      if (res && res.code === 200) {
        row.status = res.result.status
        $table.reloadRow(row, {})
        this.$message.success('设置成功！')
      } else {
        this.$message.error('设置失败！')
      }
    },
    async handleChange(row, info) {
      let fileList = info.fileList
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          fileList = fileList.map((file) => {
            if (file.response) {
              file.url = file.response.result.url[0]
              this.form.avatarUrl = file.url
              this.form.hiddenAvatar = '0'
            }
            return file
          })
        }
      } else if (info.file.status === 'error') {
        this.$message.error('上传失败')
      } else {
        fileList = fileList.slice(0, 1)
      }
      this.fileList = fileList
      if (!(fileList[0] && fileList[0].url)) {
        return
      }
      await addAttach({
        contentId: row.id,
        attachUrl: [fileList[0].url]
      })
    },
    beforeUpload(file) {
      this.headers[ACCESS_TOKEN] = this.token
      if (this.fileList.length > 0) {
        this.$message.error('只能同时上传一个文件')
        return false
      }
    },
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageSize = pageSize
      this.loadData()
    },
    async loadData() {
      const { id: schedulesId } = this.model
      this.loading = true
      const { code, result } = await getPlanNodeList(schedulesId, this.tablePage.currentPage, this.tablePage.pageSize)
      this.loading = false
      if (code === 200) {
        const res = result.content.map(item => this.formatNode(item, 2))
        this.tablePage.totalResult = result.totalElements
        this.tableData = res
      } else {
        // VXETable.modal.message({ content: '请求失败', status: 'error' })
      }
    },
    selectDept(row, column, codes, selectRow) {
      const { field } = column
      row[`_${field}`] = selectRow
    },
    selectUser(row, username, nickname, userInfo) {
      row['_userInfo'] = userInfo
      row.username = username
      row.nickname = nickname
    },
    // type : 1-fe to be 2-be to fe
    formatNode(data, type = 1) {
      const { id: schedulesId } = this.model
      if (type === 1) {
        // eslint-disable-next-line no-unused-vars
        const { leadingDept, cooperateDept, _leadingDept, _cooperateDept, _userInfo, isAdd, id, ...rest } = data
        return {
          schedulesId,
          ...rest,
          deptList: [{ deptId: _leadingDept.id, deptType: 1 }].concat((_cooperateDept || []).map(item => ({ deptId: item.id, deptType: 2 })))
        }
      } else {
        const { content, username, nickname, progress, id, startTime, endTime, deptList, status } = data
        const leadingDept = deptList.find(item => item.deptType === '1')
        const cooperateDept = deptList.filter(item => item.deptType === '2').map(item => ({ ...item, id: item.deptId }))
        if (leadingDept) {
          leadingDept.id = leadingDept.deptId
        }
        return {
          content,
          username,
          nickname,
          progress,
          id,
          startTime,
          endTime,
          status,
          attachList: [],
          leadingDept: leadingDept ? leadingDept.deptCode : null,
          cooperateDept: cooperateDept.map(item => item.deptCode).join(','),
          _leadingDept: leadingDept,
          _cooperateDept: cooperateDept,
          _userInfo: { username, nickname }
        }
      }
    },
    async insertEvent(row) {
      const { nickname, username, dept } = this.$store.state.account.user
      const $table = this.$refs.xTable
      const record = {
        content: '日常工作',
        username,
        nickname,
        leadingDept: dept.deptCode,
        cooperateDept: dept.deptCode,
        progress: 100,
        startTime: moment().subtract(7, 'days').format('YYYY-MM-DD'),
        endTime: moment().add(7, 'days').format('YYYY-MM-DD'),
        status: '0',
        isAdd: true,
        _leadingDept: dept,
        _cooperateDept: [dept],
        _userInfo: this.$store.state.account.user
      }
      const { row: newRow } = await $table.insertAt(record, row)
      $table.setActiveRow(newRow)
    },
    getPopupContainer: () => document.body,
    cancelRowEvent(row) {
      const $table = this.$refs.xTable
      $table.clearActived().then(() => {
        // 还原行数据
        $table.revertData(row)
      })
    },
    editRowEvent(row) {
      const $table = this.$refs.xTable
      $table.setActiveRow(row)
    },
    async saveRowEvent(row) {
      const req = this.formatNode(row)
      const $table = this.$refs.xTable
      this.loading = true
      if (row.isAdd) {
        // 新增
        const { code, result } = await addPlanNode(req)
        if (code !== 200) {
          this.loading = false
          // VXETable.modal.message({ content: '添加失败', status: 'error' })
          return
        }
        row.id = result.id
        row.isAdd = false
        VXETable.modal.message({ content: '添加成功', status: 'success' })
      } else {
        // 编辑
        const res = await editPlanNode({ ...req, id: row.id })
        if (res && res.code !== 200) {
          this.loading = false
          // VXETable.modal.message({ content: '保存失败', status: 'error' })
          return
        }
        VXETable.modal.message({ content: '保存成功！', status: 'success' })
      }
      $table.clearActived().then(() => {
        this.loading = false
        $table.reloadRow(row, {})
      })
    },
    async deleteRowEvent(row) {
      const type = await VXETable.modal.confirm('您确定要删除该数据?')
      const $table = this.$refs.xTable
      if (row.isAdd) {
        $table.remove(row)
        VXETable.modal.message({ content: '删除成功', status: 'success' })
        return
      }
      if (type === 'confirm') {
        this.loading = true
        const res = await deletePlanNode(row.id)
        this.loading = false
        if (res && res.code === 200) {
          $table.remove(row)
          VXETable.modal.message({ content: '删除成功', status: 'success' })
        } else {
          // VXETable.modal.message({ content: '删除失败', status: 'error' })
        }
      }
    }
  }
}
</script>

<style>
.plan-node {
  margin: 0;
}
.upload-txt {
  color: #606266;
}
.disable-txt {
  color: darkgray;
}
</style>
